import pygame

images = dict()
refcount = dict()

def loadImage(filename):
  img = None
  if filename not in images:
    try:
      img = pygame.image.load(filename)
    except pygame.error, message:
        print 'Image loading failed: ', filename
        raise SystemExit, message
    images[filename] = img
    refcount[filename] = 1
  else:
    img = images[filename]
    refcount[filename] += 1

  return img

class Image(object):

  def __init__(self, filename, interval=-1):
    self.__img = loadImage(filename)
    self.__clip = []
    self.__filename = filename
    self.__totaltime = 0
    self.__interval = interval

  def __del__(self):
    if refcount[self.__filename] == 1:
      images[self.__filename] = 0

    refcount[self.__filename] -= 1

  def draw(self, graphics, coord):
    tempclip = self.size()

    if len(self.__clip) > 0:
      if self.__interval > 0:
        tempclip = self.__clip[((self.__totaltime/self.__interval) % len(self.__clip))]
      else:
        tempclip = self.__clip[0]

    graphics.drawImage(self, coord, tempclip)

  def update(self, time):
    if self.__interval > 0:
      self.__totaltime += time

  def pushClip(self, clip):
    self.__clip.append(clip)

  def popClip(self, index):
    return self.__clip.pop(index)

  def size(self):
    return pygame.Rect(0, 0, self.__img.get_width(), self.__img.get_height())

  def getSurface(self):
    return self.__img

  def setInterval(self, interval):
    self.__interval = interval

  def __getstate__(self):
    result = self.__dict__.copy()
    del result['_Image__img']
    del result['_Image__totaltime']
    return result

  def __setstate__(self, dict):
    self.__dict__ = dict
    self.__img = loadImage(self.__filename)
    self.__totaltime = 0
